package org.prail.ui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import org.prail.threads.DownloadThread;
import org.prail.ui.utils.CustomProgressBar;
import org.prail.wrappers.SearchResult;

public class DownloadTable extends JTable {
	private static final long serialVersionUID = 6464098497169279412L;
	private static DefaultTableModel model = new DefaultTableModel();
	private static DownloadTable instance = null;
	private static HashMap<Integer, SearchResult> tableList = new HashMap<Integer, SearchResult>();

	public DownloadTable() {
		super();
		instance = this;
		getTableHeader().setReorderingAllowed(false); // disable moving columns
		setModel(model);
		updateModel();
		addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					final SearchResult selected = tableList.get(row);
					System.out.println("Opening: " + selected.toString());
					try {
						// windows only for now
						Runtime.getRuntime().exec
						  ("rundll32 SHELL32.DLL,ShellExec_RunDLL " + selected.getSaveFile().getAbsolutePath());
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
		});
	}

	private void updateModel() {
		model.addColumn("Artist");
		model.addColumn("Title");
		model.addColumn("Length");
		model.addColumn("Status");
		TableColumn c = getColumnModel().getColumn(2); // length column
		getColumnModel().getColumn(3).setCellRenderer(new CustomProgressBar());
		c.setMaxWidth(70); // max width
		c.setMinWidth(50); // min width
		c = getColumnModel().getColumn(3);
		c.setMinWidth(120);
		c.setMaxWidth(120);

	}
	
	public static int getRow(SearchResult r) {
		for(int a : tableList.keySet()) {
			if(tableList.get(a).equals(r)) {
				return a;
			}
		}
		return -1;
	}

	public static DownloadTable get() {
		return instance;
	}

	public void download(final SearchResult r) {
		final CustomProgressBar bar = new CustomProgressBar();
		final Object[] row = new Object[] { r.getArtist(), r.getTitle(),
				r.getLength(), bar };
		model.addRow(row);
		tableList.put(tableList.size(), r);
		new DownloadThread(bar, r, 0).start();
	}

	@Override
	public boolean isCellEditable(int rowIndex, int vColIndex) {
		return false;
	}

}
